<template>
  <div class="cate-add-container" style="max-width: 800px">
    <el-form ref="itemAdd" :model="item" label-width="120px" :rules="rules">
      <el-form-item label="商品名" prop="itemName">
        <el-input v-model="item.itemName" />
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input-number v-model="item.price" :min="0" />
      </el-form-item>
      <el-form-item label="是否上架" prop="onsale">
        <el-switch
          inline-prompt
          v-model="item.onsale"
          active-text="上架"
          inactive-text="下架"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="cateId">
        <el-cascader
          v-model="item.cateId"
          :options="cates"
          :props="{
            checkStrictly: true,
            label: 'cateName',
            value: 'id',
            emitPath: false,
          }"
          clearable
        />
      </el-form-item>
      <el-form-item label="图片(第一个自动选为封面)">
        <el-upload
          v-model:file-list="fileList"
          action="/api/upload"
          name="file"
          accept=".jpg,.png,.gif"
          list-type="picture-card"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input type="textarea" v-model="item.desc" />
      </el-form-item>
      <el-form-item label="详情">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="item.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css";
import { fetchCateLists } from "@a/cate";
import { updateItem, fetchItemDeatil } from "@a/item";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
export default {
  name: "ItemAdd",
  data() {
    return {
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          uploadImage: {
            server: "/api/upload",
            fieldName: "file",
            customInsert(res, insertFn) {
              insertFn(res.data.url);
            },
          },
        },
      },
      mode: "default", // or 'simple'
      fileList: [],
      rules: {
        itemName: [
          {
            required: true,
            message: "商品名必填",
          },
        ],
        price: [
          {
            type: "number",
            required: true,
            message: "商品价格必填",
          },
        ],
        cateId: [
          {
            required: true,
            message: "商品分类必填",
          },
        ],
      },
      item: {
        itemName: "",
        price: 0,
        onsale: true,
        desc: "",
        pics: [],
        cateId: -1, // 当前商品的分类
        content: "",
      },
      // 所有的分类
      cates: [],
    };
  },
  methods: {
    // 获取修改商品详情
    fetchItemDetail() {
      fetchItemDeatil(this.$route.query.id).then((res) => {
        if (res.data.code === 200) {
          this.item = res.data.data;
          this.item.pics.forEach((img) => {
            this.fileList.push({
              name: "xxx",
              url: img,
            });
          });
        }
      });
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    resetForm() {
      // 重置表单的
      this.$refs.itemAdd.resetFields();
    },
    onSubmit() {
      this.$refs.itemAdd
        .validate()
        .then(() => {
          updateItem(this.item).then((res) => {
            if (res.data.code === 200) {
              this.$message({
                type: "success",
                message: res.data.msg,
                duration: 1500,
                onClose: () => {
                  // 跳转到列表页
                  this.$router.replace("/itemLists");
                },
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "表单校验不通过",
          });
        });
    },
    beforeUpload(file) {
      // 1m
      if (file.size > 1024 * 1024) {
        this.$message({
          type: "error",
          message: "请选择小于1m图片",
        });
        return false;
      } else {
        return true;
      }
    },
    uploadSuccess(res) {
      if (res.code === 200) {
        this.item.pics.push(res.data.url);
        this.$message({
          type: "success",
          message: "上传成功",
        });
      }
    },
    fetchCateLists() {
      // 请求商品分类
      fetchCateLists().then((res) => {
        if (res.data.code === 200) {
          this.cates = res.data.data;
          this.item.cateId = this.cates[0].id;
        }
      });
    },
  },
  created() {
    this.fetchCateLists();
    this.fetchItemDetail();
  },
  components: { Editor, Toolbar },
};
</script>

<style lang="scss" scoped></style>
